package com.jhc.drone.communication.network.udp;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

@Slf4j
public class UdpResponseSender {


    public static void sendResponse(byte[] data, Channel channel) {
        ByteBuf byteBuf = Unpooled.copiedBuffer(data);
        InetSocketAddress socketAddress = (InetSocketAddress) channel.remoteAddress();
        DatagramChannel datagramChannel = null;

        try {
            // 创建一个DatagramChannel，如果已经有DatagramChannel，可以跳过这一步
            datagramChannel = DatagramChannel.open();

            // 设置为非阻塞模式
            datagramChannel.configureBlocking(false);

            // 将ByteBuf转换为ByteBuffer进行发送
            ByteBuffer byteBuffer = byteBuf.nioBuffer();

            // 发送数据包到指定的客户端地址
            int bytesSent = datagramChannel.send(byteBuffer, socketAddress);

            if (bytesSent > 0) {
                log.info("Successfully sent {} bytes to {}", bytesSent, socketAddress);
            } else {
                log.warn("Failed to send data to {}", socketAddress);
            }
        } catch (IOException e) {
            log.error("Failed to send response to UDP client: {}", e.getMessage());
        } finally {
            // 关闭DatagramChannel，避免资源泄漏
            if (datagramChannel != null && datagramChannel.isOpen()) {
                try {
                    datagramChannel.close();
                } catch (IOException e) {
                    log.error("Failed to close DatagramChannel: {}", e.getMessage());
                }
            }
        }
    }
}
